<template>
  <div class="main">
    <div class="flexBetween " style="margin-bottom: 20px;">
      <div class="flex default">
        <div class="flex">
          <div style="margin:0 10px 0 20px;text-align: center;">采购单名:</div>
          <el-input prefix-icon="el-icon-search" style="width: 200px" size='small' v-model="serachOrderName" clearable
                    placeholder="请输入采购单名称"></el-input>
        </div>
        <div class="flex">
          <div style="margin:0 10px 0 20px;text-align: center;">采购单号:</div>
          <el-input prefix-icon="el-icon-search" style="width: 200px" size='small' v-model="procureId" clearable
                    placeholder="请输入采购单号"></el-input>
        </div>
        <div class="flex">
          <div style="text-align: center;margin:0 10px 0 20px">仓库:</div>
          <el-select v-model="searchWarehouseId"  size='small' clearable style="width:200px" placeholder="请选择">
            <el-option v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName"
                       :value="item.warehouseId">
            </el-option>
          </el-select>
        </div>
        <!-- <el-button @click="downloadAll">全量导出</el-button> -->
        <el-button style="margin-left: 10px;" size='small' @click="searchProcureList" type="primary">查询</el-button>
      </div>
      <div class="default">
        <el-button @click="createStatus = true " size='small' type="primary">新增采购单</el-button>
        <!-- <el-button >导出采购单</el-button> -->
      </div>

    </div>
    <el-table element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" v-loading='loading'
              height="calc(100vh - 250px)" stripe border :data="procureList" tooltip-effect="dark" style="width: 100%"
              :header-cell-style="{  'fontSize': '14px', 'background-color': '#F3F6FD', 'color': '#333333', 'textAlign': 'center' }"
              :cellStyle="{
            'textAlign': 'center',
            'fontSize': '12px'
          }">
      <el-table-column label="采购单号" prop="procureId" min-width="130px"></el-table-column>
      <el-table-column label="名称" prop="orderName" min-width="80px">
      </el-table-column>
      <el-table-column label="采购时间" prop="buyTime" width=""></el-table-column>
      <el-table-column label="材料明细" min-width="400px">
        <template slot-scope="scope">
          <el-table stripe border :data="scope.row.classifications" tooltip-effect="dark"
                    maxHeight="300px"
                    style="width: 100%;" :headerCellStyle="{
            'textAlign': 'center',
            'fontSize': '12px'
          }" :cellStyle="{
            'textAlign': 'center',
            'fontSize': '12px'
          }">
            <el-table-column label="名称" prop="classification.name" min-width="100px"></el-table-column>
            <!-- <el-table-column label="规格" prop="norm" min-width="140px"></el-table-column>
            <el-table-column label="颜色" prop="color" min-width="140px"></el-table-column> -->
            <el-table-column label="采购数量" prop="count" min-width="100px"></el-table-column>
            <el-table-column label="单价" prop="price" min-width="100px"></el-table-column>
            <!-- <el-table-column label="已入库" prop="price" min-width="140px"></el-table-column>
            <el-table-column label="未入库" prop="price" min-width="140px"></el-table-column> -->
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="合计金额" prop="materialTotalPrice" min-width="80px"></el-table-column>
      <!-- <el-table-column label="已付金额" prop="payAmountPrice" min-width="80px"></el-table-column>
      <el-table-column label="未付金额" prop="balancePayment" width="80px"></el-table-column> -->
      <el-table-column label="已付金额" prop="paymentAmount" min-width="80px"></el-table-column>
      <el-table-column label="未付金额" prop="waitPayAmountPrice" min-width="80px"></el-table-column>
      <el-table-column label="采购凭证" width="150px">
        <template slot-scope="scope">
          <el-image v-for='(v, i) in scope.row.procureVouchersList' :key="i" style="width: 50px; height: 50px"
                    ref="preview" :src="'https://'+v" :preview-src-list="['https://'+v]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" width="200px" show-overflow-tooltip></el-table-column>
      <el-table-column label="仓库" width="60px">
        <template slot-scope="scope">
          {{ scope.row.warehouse.warehouseName }}
        </template>
      </el-table-column>
      <el-table-column label="仓库管理员" min-width="100px">
        <template slot-scope="scope">
          {{ scope.row.warehouse.warehouseManager }}
        </template>
      </el-table-column>
      <el-table-column label="发起人">
        <template slot-scope="scope">
          {{ scope.row.user.userName }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createdAt" width="160px"></el-table-column>
      <el-table-column fixed="right" label="入库状态">
        <template slot-scope="scope">
          <el-tag type='success' v-if="scope.row.arrivalStatus">已入库</el-tag>
          <el-tag type='danger' v-else @click="statusChange(scope.row), 'arrvial'"> 未入库</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="付款状态">
        <template slot-scope="scope">
          <el-tag type='success' v-if="scope.row.paymentStatus">已支付</el-tag>
          <el-tag type='danger' v-else @click="statusChange(scope.row, 'pay')">未支付</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="140">
        <template slot-scope="scope">
          <div>
            <div v-if="['admin'].includes(userName)">
              <el-link style="color: #303e9d" @click="deletaProcure(scope.row.procureId)" v-if="authorityList.includes(1201)">删除</el-link>
            </div>
            <div v-if="userName === 'admin'">
              <el-link style="color: #303e9d" @click="editProcureInfo(scope.row)" v-if="authorityList.includes(1202)">编辑</el-link>
            </div>
            <div>
              <el-link style="color: #303e9d" @click="importProcureBtn(scope.row)" v-if="authorityList.includes(1203)">录入付款</el-link>
            </div>
<!--            <div>-->
<!--              <el-link color="#333" @click="changeProcureInfo(scope.row)">变更明细</el-link>-->
<!--            </div>-->
            <div>
              <el-link style="color: #303e9d" @click="proDetailsBtn(scope.row.procureId, 'pay')" v-if="authorityList.includes(1204)">付款明细</el-link>
            </div>
            <div>
              <el-link style="color: #303e9d" @click="proDetailsBtn(scope.row.procureId, 'arrvied')" v-if="authorityList.includes(1205)">入库明细</el-link>
            </div>
            <div>
              <el-link style="color: #303e9d" v-if='authorityList.includes(1206)&&!scope.row.arrivalStatus'
                       @click="laidUpBtn(scope.row)" >操作入库
              </el-link>
            </div>
            <!-- <div>
              <el-link type="primary" @click="exportExcel(scope.row)">导出数据</el-link>
            </div> -->
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination align="center" style="margin-top: 20px;" @size-change="handleSizeChange"
                   @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20,30,40,50]"
                   layout="total, sizes, prev, pager, next, jumper" :total="totalCount">
    </el-pagination>

    <el-dialog :visible.sync="createStatus" width="80%" style="padding-top: 0;">
      <div>
        <div style="background-color: white;">
          <img src="@/assets/img/header0.png" style="width:100%;">
          <div class="title" style="">新增采购单</div>
        </div>
        <el-card style="margin-top:10px">
          <div style="justify-content: space-between;display: flex;">
            <div style="width: calc(100% - 400px);">
              <div style="display: grid;grid-template-columns: repeat(3,1fr);grid-gap:30px">
                <div>
                  <div class="dataInput">采购单名称 <span style="color: red;">*</span></div>
                  <el-input v-model="orderName" placeholder="请输入采购单名称"></el-input>
                </div>
                <div>
                  <div class="dataInput">采购日期 <span style="color: red;">*</span></div>
                  <el-date-picker style="width: 100%;" @change="buyTimeFunc" v-model="buyTime" type="date"
                                  placeholder="选择日期">
                  </el-date-picker>
                </div>
                <div>
                  <div class="dataInput">采购仓库 <span style="color: red;">*</span></div>
                  <el-select v-model="warehouseId" style="width:100%" placeholder="请选择">
                    <el-option v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName"
                               :value="item.warehouseId">
                    </el-option>
                  </el-select>
                </div>
              </div>
              <div
                  style="display: grid;grid-template-columns: repeat(3,1fr);grid-gap:30px;margin:40px 0;margin-top: 80px;">

                <!-- <div>
                  <div class="dataInput">预估物流时效(天) <span style="color: red;">*</span></div>
                  <el-input v-model="posterTime" placeholder="请输入预估物流时效"></el-input>
                </div> -->
                <div>
                  <div class="dataInput">备注 <span style="color: red;">*</span></div>
                  <el-input type='textarea' height="40px" v-model="addProcureRemark" placeholder="请输入备注"></el-input>
                </div>
              </div>
            </div>
            <div style="width: 360px;">
              <div class="dataInput">下单凭证 <span style="color: red;">*</span></div>
              <div>
                <rayUpload @url="getImageUrl"></rayUpload>
              </div>
            </div>
          </div>
          <div class="table">
            <div class="dataInput">采购明细</div>
            <el-table border stripe height="40vh" :data="tableData" tooltip-effect="dark" style="width: 100%"
                      :headerCellStyle="{
            'textAlign': 'center'
          }" :cellStyle="{
            'textAlign': 'center',
            'fontSize': '12px'
          }">
              <el-table-column label="ID" min-width="60">
                <template slot-scope="scope">
                  <div>{{ scope.row.classificationId }}</div>
                </template>
              </el-table-column>
              <el-table-column label="分类名称" min-width="220">
                <template slot-scope="scope">
                  <div>{{ scope.row.name }}</div>
                </template>
              </el-table-column>
              <el-table-column label="单位" min-width="220">
                <template slot-scope="scope">
                  <div>{{ scope.row.unit }}</div>
                </template>
              </el-table-column>
              <el-table-column label="单价" width="240">
                <template slot-scope="scope">
                  <el-input-number @change="countChange" :disabled="scope.row.count == 0" v-model="scope.row.price"
                                   :min="0"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="数量" width="240">
                <template slot-scope="scope">
                  <el-input-number @change="countChange" :precision="0" v-model="scope.row.count"
                                   :min="0"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="小计总价" min-width="120">
                <template slot-scope="scope">
                  <div v-if="scope.row.TotalUnitPrice">
                    {{ scope.row.TotalUnitPrice }}元
                  </div>
                  <div v-else>
                    0元
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="margin-top: 10px;text-align: center;font-size: 18px;">
            金额汇总:<span style="font-size: 20px;color:#303e9d;margin:5px 0;">{{ allCount }}</span>元
          </div>
        </el-card>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitOrder">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 录入到货/付款凭证/材料入库 -->
    <el-dialog :visible.sync="importProcure" @close="close" :title="`录入${importType}`" width="60%"
               style="padding-top: 0;">
      <div>
        <el-descriptions v-if="this.importMaterialInfo">
          <el-descriptions-item label="采购单名称">{{ importMaterialInfo.orderName }}</el-descriptions-item>
          <el-descriptions-item label="发起日期">{{ importMaterialInfo.createdAt }}</el-descriptions-item>
          <el-descriptions-item label="仓库">{{ importMaterialInfo.warehouse.warehouseName }}</el-descriptions-item>
          <el-descriptions-item label="采购总价">{{ importMaterialInfo.materialTotalPrice }}</el-descriptions-item>
          <el-descriptions-item label="发起人">
            <el-tag type="warning" size="small">{{ importMaterialInfo.user.userName }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{ importMaterialInfo.remark }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div style="display:flex;">
        <div style="margin-top:20px;width:350px;margin-right: 20px;" v-if="this.importType == '付款凭证'">
          <div>
            <div style="margin-bottom: 10px;margin-top: 10px;">
              付款金额<span style="color:red;">*</span> <el-input type="number" v-model.trim="sendInput" style="width: 200px"></el-input>
            </div>

          </div>
          <div>
            <div style="margin-bottom: 10px;margin-top:20px">
              付款时间<span style="color:red;">*</span>
              <el-date-picker style="width: 200px;margin-left: 3px" @change="paymentFunc" v-model="paymentTime" type="date"
                                                                     placeholder="选择日期">
            </el-date-picker>
            </div>

          </div>
        </div>
        <!-- <div v-if="importType == '付款凭证'">
          <div>付款凭证 <span style="color:gray;font-size: 12px;">(粘贴复制即可上传图片)</span></div>

              <el-image v-for='(v, i) in imageListPreview' :key="i" style="width: 50px; height: 50px"
                      ref="preview" :src="host + v" :preview-src-list=" imageListPreview">

            </el-image>
        </div> -->
        <div style="margin-bottom: 20px;">
          <div><span v-if="importType == '材料入库信息'">入库凭证</span>
            <span v-else>付款凭证</span>
            <span style="color:gray;font-size: 12px;">(粘贴复制即可上传图片)</span></div>
          <el-image v-for='(v, i) in imageListPreview' :key="i" style="width: 50px; height: 50px"
                    ref="preview" :src="'https://'+v" :preview-src-list="['https://'+v]">

          </el-image>
        </div>
        <!-- <rayMulImageUpload  tyle="width: calc(100% - 400px);" type="procure" @imageList="imageList"
                          @clear="imageListclear" v-if="importProcure && importType !== '付款凭证'">
       </rayMulImageUpload>  -->
      </div>

      <div style="margin-bottom: 10px;" v-if="this.importType == '材料入库信息'">
        材料入库<span style="color:red;">*</span>
      </div>
      <div v-if="this.importType == '材料入库信息'" class="materialIncountTable">
        <div class='materialIncountTableItem' v-for="(v, i) in inCountMaterialList" :key="i">
          <div style="width: 100px;">
            {{ v.name }}
          </div>
          <div style="padding:10px 30px;width:400px;border-left: 0.5px solid #eee;border-right: 0.5px solid #eee;">
            <el-select v-model="v.materialId" style="width:100%">
              <el-option v-for="item in v.materials" :key="item.materialId"
                         :label="'编码:' + item.materialId + item.color + item.norm + item.unit + item.price"
                         :value="item.materialId"></el-option>
            </el-select>
          </div>
          <el-input-number v-model="v.count" :min="0"></el-input-number>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sendVoucher">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog class='default' :visible.sync="editProcureOrderStatus" title="编辑采购订单" width='400px'>
      <el-form :model="editInfo" :rules="editRules" ref="editInfo" label-width="100px">
        <el-form-item label="采购单名称" required prop="orderName">
          <el-input clearable  v-model="editInfo.orderName" placeholder="请输入采购单名称"></el-input>
        </el-form-item>
        <el-form-item label="备注" required prop="remark">
          <el-input clearable type='textarea' v-model="editInfo.remark" placeholder="请输入备注"></el-input>
        </el-form-item>
        <el-form-item label="销售时间">
          <el-date-picker style="width: 100%;" v-model="editInfo.buyTime" type="date">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div style="display: flex;align-items: center;margin-bottom: 50px">
        <!--        <div style="width:100px;text-align: center;margin-top: 30px">凭：</div>-->
        <div>
          <span style="color:gray;font-size: 12px;">(粘贴复制即可上传图片)</span>
          <div class="div" style="display: flex;align-items: center">
            <div v-for='(v, i) in preSalesImg' style="display: flex;align-items: center;margin-right: 10px;">
              <el-image :key="i" style="width: 50px; height: 50px"
                        ref="preview" :src="'https://'+v" :preview-src-list="['https://'+v]">
              </el-image>
              <div @click="deletePic(i)">
                <el-icon name="delete"></el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
      <el-button style="width: 100%;margin-top: 20px;" type="primary" @click="submitForm('editInfo')">立即创建</el-button>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="statusChangeDialog" width="30%">
      <span>{{ statusChangeDialogTitle }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="statusChangeConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <proDetails v-if="proDetailsStatus" @confirm="confirm" :proDetailsType="detailsTitle"
                :proDetailsStatus="proDetailsStatus" :proDetailsId="proDetailsId" />

    <changeBox @close="changeBoxClose" apiName="changeSelectChangeDetailList" v-if="changeBoxStatus"
               :targetId="targetId"></changeBox>
  </div>
</template>
<script>
import dayjs from "dayjs";
import axios from 'axios';
import changeBox from '@/RayComponents/materialChange.vue'
import Decimal from "decimal.js";
import rayUpload from '@/RayComponents/rayUpload.vue'
import * as Ray from '../../utils/public'
import XLSX from 'xlsx-js-style'
import rayMulImageUpload from '@/RayComponents/rayMulImageUpload.vue'
import proDetails from "@/RayComponents/proDetails.vue";
import quinn from "@/utils/quinn";

export default {
  name: "ProcureList",
  components: {
    rayUpload,
    proDetails,
    rayMulImageUpload,
    changeBox
  },
  // meta: { title: "采购单列表", icon: "el-icon-s-order",  authorityList:1200,sort:11},
  data() {
    return {
      changeBoxStatus: false,//变更记录开关
      proDetailsId: '',
      listChange: ['admin', '闵祥杰', '陶克勤', '陈晢翰'],
      addProcureRemark: '',
      proDetailsStatus: false,
      detailsTitle: '',
      apiName: "procureProcureList",
      targetId: '',
      posterEndTime: '',//到货日期
      posterTime: '', //物流时效
      buyTime: '', //采购日期
      paymentTime: '',//录入付款时 付款时间
      searchWarehouseId: '',//查询时候的仓库id
      warehouseId: '',//下单仓库
      warehouseList: '',//仓库列表
      createStatus: false,
      importProcure: false,
      sendInput: '',
      laidUpStatus: false,//入库开关
      importMaterialInfo: null,//到货材料预览
      importType: '付款',
      multipleSelection: [],
      preSalesImgList: [],
      totalCount: 0,
      allCount: 0,
      loading: false,
      editProcureOrderStatus: false,
      editInfo: {
        orderName:"",
        remark: '',
        procureId: '',
        buyTime: ''
      },
      editRules: {
        // remark: [
        //   { required: true, message: '请输入备注', trigger: 'blur' },
        //   { min: 2, message: '请输入备注', trigger: 'blur' }
        // ],
      },
      pageNumber: 1,
      pageSize: 20,
      procureId: '',
      serachOrderName: '',
      procureStartTime: '',
      preSalesImg: [],
      procureEndTime: '',
      procureList: [],
      userName: '',
      procureImage: '',
      currentPage: 1,
      maxHeight: 0,
      supplierList: [],//供应商列表
      supplierId: '',//选中的供应商id
      supplierName: '',//选中的供应商名称
      statusChangeDialog: false,
      statusChangeDialogTitle: '',
      statusChangeDialogType: '',
      statusChangeDialogInfo: '',
      tableData: [],
      orderName: '',
      host: this.$imgHost,
      imageListPreview: [], //凭证默认图片
      imageListPreviewTest: [], //凭证默认图片
      imageListclear: false,
      inCountMaterialList: [],//操作入库分类及材料列表
      authorityList:[]
    };
  },
  computed: {},
  mounted() {
    this.$nextTick(() => {
      this.maxHeight = window.innerHeight - 240;
    })
    window.onresize = () => {
      this.$nextTick(() => {
        this.maxHeight = window.innerHeight - 240;
      })
    }
  },
  directives: {
    focus: {
      inserted: function (el) {
        el.querySelector('input').focus()
      }
    }
  },
  created() {
    this.getProcureList();
    this.getWarehouse();
    const {authorityList = [],userName = []} = quinn.getStorage("userDatav3") || store.state.userData || {};
    this.authorityList = authorityList
    // const { userName = [] } =
    // quinn.getStorage("userDatav3") || store.state.userData || {};
    this.userName = userName;
    this.getCateList();
    document.addEventListener('paste', this.handlePaste)
  },

  methods: {
    cellClick(row, column) {
      if (column.label === '名称') {
        row.isNameSelect = true
      }
      console.log(row.isNameSelect)
    },
    //修改列表门店名称
    blurEvent(row, curIndex, column) {
      const data = {
        storeName: row.storeName,
        saleId: row.saleId,
        saleType: row.saleType
      }
      this.$api.saleUpdateSaleStoreName(data)
      row.isNameSelect = false
    },
    focusEvent() {

    },
    imageList(e) {
      // this.imageList = e;
      this.imageListPreview.push(e);

    },
    deletePic(i) {
      this.preSalesImg.splice(i, 1)
    },
    handlePaste(event) {
      if (!(this.importProcure || this.editProcureOrderStatus)) return;
      const clipboardData = event.clipboardData || window.clipboardData;
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i];

          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile();
            if (file) {
              this.uploadImage(file);
            }
          } else {
            this.$message.error('请拷贝图片!');
            break;
          }
        }
      }
    },
    uploadImage(imageFile) {
      const formData = new FormData();
      formData.append('file', imageFile);
      axios.post(`${this.$apiHost}/img/fileImgUrl`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token': window.$quinn.getStorage("tokenv3")
        }
      })
          .then(response => {
            console.log()
            this.imageListPreviewTest.push(response.data.result[0]);
            this.imageListPreview.push(response.data.result[0]);
            this.preSalesImg.push(response.data.result[0]);
            //this.preSalesImgList.push(this.host + response.data.data[0]);
          })
          .catch(error => {
            console.error('Upload failed:', error);
          });
    },
    downloadAll() {
      let params = {
        pageNumber: 1,
        pageSize: 1000000,
        warehouseId: 1,//云南5 贵州11
        type: 'web'
      }
      this.$api.procureProcureList(params).then(res => {
        let startTime = '2024-05-01'
        let endTime = '2024-06-13'
        let dataArr = []

        // && el.outStatus == 1
        res.rows.map(el => {
          let time = el.buyTime

          if (time >= startTime && time <= endTime) {
            dataArr.push(el);
          }
        })

        let demoDataArr = [];
        dataArr.map(el => {
          this.$api.procureProcureMaterials({ 'procureId': el.procureId }).then(res => {
            // res[0].materialName = el.materialName
            demoDataArr.push(res);
          })
        })
        setTimeout(() => {
          const wb = XLSX.utils.book_new();
          let data = [['商品编码', '商品数量', '数量', '店名']]

          demoDataArr.map(el => {
            el.map(k => {
              data.push([k.materialId, k.materialName, k.count, k.createdAt])
            })
          })
          const ws = XLSX.utils.aoa_to_sheet(data);
          ws['!cols'] = [
            { wpx: 200 }, // 第一列宽度为250单位
            { wpx: 200 }, // 第二列宽度为300单位
            { wpx: 100 },  // 第三列宽度为350单位
            { wpx: 100 },
            { wpx: 100 },
            { wpx: 100 }
          ];
          // 将工作表添加到工作簿
          XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

          // 导出工作簿为 Blob 对象
          const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

          // 创建一个 Blob 对象
          const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });

          // 使用 Blob 对象创建一个链接
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          let warehouseName = '宁乡仓'


          link.download = `${warehouseName}-${new Date().getTime()}.xlsx`;


          // 触发下载
          link.click();

          // 清理
          URL.revokeObjectURL(link.href);

          function s2ab(s) {
            const buf = new ArrayBuffer(s.length);
            const view = new Uint8Array(buf);
            for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
          }


        }, 5000)
      })

    },
   async submitForm() {
      confirm
      if (this.editInfo.buyTime) {
        this.editInfo.buyTime = dayjs(this.editInfo.buyTime).format('YYYY-MM-DD');
      } else {
        this.$message.error('请选择时间!');
        return;
      }
      const data = {
        ...
            this.editInfo,
        procureVouchers: this.preSalesImg.toString()
      }
    const res=await this.$api.procureProcureInfoUpdate(data).then()
     this.$message.success('修改成功')
     this.editProcureOrderStatus=false
     this.getProcureList()
    },
    editProcureInfo(info) {
      console.log(info, "info")
      this.editProcureOrderStatus = true;
      this.editInfo.remark = info.remark;
      this.editInfo.orderName = info.orderName;
      this.editInfo.buyTime = info.buyTime;
      this.preSalesImg = info.procureVouchers || [];
      info.procureVouchers.map(k => {
        this.preSalesImgList.push(this.$imgHost + k);
      })
      this.editInfo.procureId = info.procureId;
    },
    confirm() {
      this.proDetailsStatus = false;
    },
    // imageList(e) {
    //   // this.imageList = e;
    //   this.imageListPreview.push(e);

    // },

    close() {
      this.createStatus = false;
      this.importProcure = false;
      this.allCount = 0;
      this.buyTime = '';
      this.addProcureRemark = '';
      this.orderName = '';
      this.warehouseId = '';
      this.imageListPreview = [];
      this.imageListPreviewTest = [];
      this.paymentTime = '';
      this.sendInput = '';
      this.tableData.map(el => {
        el.count = 0
      })
    },
    changeBoxClose(e) {
      this.changeBoxStatus = e;
    },

    changeProcureInfo(info) {
      this.targetId = info.procureId;
      this.changeBoxStatus = true;
    },
    deletaProcure(id) {
      this.$alert(`删除ID为:${id}采购单`, '提示', {
        confirmButtonText: '确定',
        callback: (res) => {
          if (res === 'confirm') {
            let params = {
              procureId: id
            }
            this.$api.procureProcureDelete(params).then(res => {
            })
            this.getProcureList();
          }
        }
      });
    },
    proDetailsBtn(info, type) {
      if (type == 'pay') {
        this.detailsTitle = '付款明细'
      } else if (type == 'arrvied') {
        this.detailsTitle = '入库明细'
      }
      this.proDetailsId = info;
      this.proDetailsStatus = true;
    },
    statusChange(info, type) {
      this.statusChangeDialog = true;
      if (type == 'pay') {
        this.statusChangeDialogTitle = `确定将采购单号${info.procureId}状态修改为已付款?`
      } else {
        this.statusChangeDialogTitle = `确定将采购单号${info.procureId}状态修改为已入库?`
      }
      // this.statusChangeConfirm(info);
      this.statusChangeDialogInfo = info;
      this.statusChangeDialogType = type;
    },
    statusChangeConfirm() {
      if (this.statusChangeDialogType == 'pay') {
        this.payMentBtn(this.statusChangeDialogInfo);
      } else {
        this.arrivedWareBtn(this.statusChangeDialogInfo);
      }
    },
    arrivedWareBtn(info) {
      let params = {
        procureId: info.procureId,
        arrivalStatus: 2
      }
      this.$api.procureProcureUpdate(params).then(res => {
        this.statusChangeDialog = false;
        this.getProcureList();
      })
    },
    payMentBtn(info) {
      let params = {
        procureId: info.procureId,
        paymentStatus: 1
      }
      this.$api.procureConfirmPayment(params).then(res => {
        this.statusChangeDialog = false;
        this.getProcureList();

      })
    },
    importProcureClose() {
      this.imageListPreview = [];
      this.importProcure = false;
    },
    importProcureBtn(e) {
      this.importType = '付款凭证'
      this.importProcure = true;
      this.importMaterialInfo = { ...e }
    },
    importGetMaterialBtn(e) {
      this.importType = '到货凭证'
      this.importProcure = true;
      this.importMaterialInfo = { ...e }
    },
    laidUpBtn(e) {
      this.importType = '材料入库信息'
      this.importProcure = true;
      this.importMaterialInfo = { ...e }
      let params = {
        procureId: this.importMaterialInfo.procureId
      }
      this.$api.procureMaterials(params).then(res => {
        res.map(el => {
          el.materialId = '';
          el.count = 0;
          if (el.materials.length > 0) {
            el.materials.map(k => {
              if (k.color == '/') {
                k.color = ' 颜色:暂无';
              } else {
                k.color = ' 颜色:' + k.color
              }
              if (k.norm == '/') {
                k.norm = ' 规格:暂无'
              } else {
                k.norm = ' 规格:' + k.norm
              }
              if (k.price == '/') {
                k.price = ' 成本价:暂无'
              } else {
                k.price = ' 成本价:' + k.price
              }
              if (k.unit == '/') {
                k.unit = ' 单位:暂无'
              } else {
                k.unit = ' 单位:' + k.unit
              }
            })
          }
        })
        this.inCountMaterialList = res;
      })
    },
    //提交凭证
    sendVoucher() {
      if (this.importType == '付款凭证') {
        this.procureIdSendPaymentVoucher();
      } else {
        let params = {
          inVouchers: this.imageListPreview.join(',') || 'none',
          procureId: this.importMaterialInfo.procureId
        }
        let data = []
        this.inCountMaterialList.map(el => {
          if (el.count > 0 && el.materialId != '') {
            data.push({ 'count': el.count, 'id': el.materialId })
          }
        })
        params.classifications = data;
        this.$api.procureProcureMaterialsIn(params).then(res => {
          this.importProcure = false;
          this.getProcureList();
        })
      }

    },
    procureIdSendPaymentVoucher() {

      if (typeof Number(this.sendInput) !== 'number') {
        this.$message.error('请填写正确的金额!');
        return;
      }
      if (this.paymentTime == '') {
        this.$message.error('请填写正确的付款日期!');
        return;
      }
      let params = {
        procureId: this.importMaterialInfo.procureId,
        paymentVouchers: this.imageListPreview.join(','),
        paymentAmount: this.sendInput,
        paymentTime: this.paymentTime
      }
      this.$api.procureProcurePaymentAdd(params).then(res => {
        this.importProcure = false;
        this.getProcureList();
      })
    },
    exportExcel(info) {
      let procureInfo = {
        procureId: info.procureId,
        orderName: info.orderName,
        createdAt: info.createdAt,
        materialTotalPrice: info.materialTotalPrice,
        materials: info.materials,
        balancePayment: info.balancePayment,
        supplierName: info.supplier.supplierName,
        remark: info.remark,
        warehouse: info.warehouse.warehouseName
      }
      //  return;
      const headerArr = ['procureId', 'orderName', 'createdAt', 'materialTotalPrice', 'materials', 'balancePayment', 'supplierName', 'warehouse', 'remark']
      const newHeaderArr = ['采购单号', '采购单名称', '发起日期', '总价', '材料明细', '未付金额', '供应商', '仓库', '备注']
      // 把对象数组转换成工作表，表头顺序按照headerArr的顺序
      const ws = XLSX.utils.json_to_sheet([procureInfo], { header: headerArr })
      // 创建新的工作簿，0.20.1版本的sheetJs可以支持传参，但当前使用的是0.18.5版本，不支持传参
      const wb = XLSX.utils.book_new();
      // 把第一行的表头(newHeaderArr )替换成实际需要展示的表头
      XLSX.utils.sheet_add_aoa(ws, [newHeaderArr], { origin: "A1" });
      // 将生成的工作表添加到新的工作簿里，Sheet1是工作表的名称
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
      // 下载工作簿
      XLSX.writeFile(wb, info.createdAt + '-' + new Date().getTime() + ".xlsx");

    },
    getCateList() {
      this.$api.classificationMaterialList({ pageSize: 10000000, pageNumber: 1 ,storeType:0}).then(res => {
        res.rows.map(el => {
          el.price = 100;
          el.count = 0;
          this.tableData.push(el)

        })
      })
    },
    getImageUrl(e) {
      this.procureImage = e;
    },
    buyTimeFunc() {
      this.buyTime = dayjs(this.buyTime).format("YYYY-MM-DD");
    },
    paymentFunc() {
      this.paymentTime = dayjs(this.paymentTime).format("YYYY-MM-DD");
    },
    posterEndTimeFun() {
      this.posterEndTime = dayjs(this.posterEndTime).format("YYYY-MM-DD");
    },
    countChange() {
      this.allCount = new Decimal(0)
      this.tableData.forEach(el => {
        el.TotalUnitPrice = Decimal(el.price).mul(Decimal(el.count));
        this.allCount = Decimal(this.allCount).plus(Decimal(el.TotalUnitPrice))
      })
    },
    getWarehouse() {
      this.$api.warehouseWarehousePullDownList().then(res => {
        console.log(res,'仓库列表')
        this.warehouseList = res;
      })
    },
    getProcureList() {
      this.loading = true
      let params = {
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        warehouseId: this.searchWarehouseId,
        procureId: this.procureId,
        orderName: this.serachOrderName
      }
      this.$api.procureProcureList(params).then(res => {
        this.loading = false;
        res.rows.forEach(el => {
          if (el.createdAt) el.createdAt = dayjs(el.createdAt).format("YYYY-MM-DD HH:mm:ss");
          if (el.materialTotalPrice) el.waitPayAmountPrice = Decimal(el.materialTotalPrice).sub(Decimal(el.paymentAmount)).toString();
          el.procureVouchers = el.procureVouchers.split(',');
          el.procureVouchersList = [];
          el.procureVouchers.map(k => {
            el.procureVouchersList.push(k);
          })

        })
        this.procureList = res.rows;
        this.totalCount = res.count;

      })
    },
    selectSupplier(e) {
      this.supplierId = e;
      this.tableData = [];
      this.allCount = 0
      this.supplierList.forEach(el => {
        if (el.supplierId == this.supplierId) {
          this.supplierName = el.supplierName
        }
      })
      this.getMaterailList();
    },
    handleCurrentChange(e) {
      this.pageNumber = e;
      this.getProcureList();
    },
    handleSizeChange(e) {
      this.pageSize = e;
      this.getProcureList()
    },
    searchProcureList() {
      this.pageNumber = 1,
          // this.pageSize = 20;
          this.getProcureList();
    },
    submitOrder() {
      let info = {
        remark: this.addProcureRemark,
        warehouseId: this.warehouseId,
        procureVouchers: this.procureImage,
        expectArrivalDate: this.posterEndTime,
        expectExpressDate: this.posterTime,
        buyTime: this.buyTime,
        orderName: this.orderName,
        materialTotalPrice: Number(this.allCount)
      }
      let materialPreOrderList = [];
      this.tableData.forEach(el => {
        if (el.count > 0) {
          materialPreOrderList.push({ id: el.classificationId, count: el.count, price: el.price })
        }
      })
      info.classifications = materialPreOrderList;
      if (info.classifications.length == 0) {
        this.$message.error('请选择采购的材料!');
        return;
      } else if (info.warehouseId == '') {
        this.$message.error('请选择采购的仓库!');
        return;
      } else if (info.buyTime == '') {
        this.$message.error('请填写采购日期!');
        return;
      } else if (info.procureVouchers == '') {
        this.$message.error('请上传采购凭证!');
        return;
      }
      this.$api.procureProcureAdd(info).then(res => {
        this.buyTime = ''
        this.addProcureRemark = ''
        this.orderName = '';
        this.warehouseId = ''
        this.createStatus = false;
        this.allCount = 0;
        this.tableData.map(el => {
          el.count = 0
        })
        this.getProcureList();
      })
    },
  },
};
</script>

<style lang="less" scoped>
@import "../../assets/css/public.css";
.main {
  font-size: 12px;
}
.title {
  padding: 20px 20px;
  margin-top: -10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  font-size: 18px;
  font-weight: 600;
}

.dataInput {
  margin-bottom: 10px;
  font-weight: 800;

}

.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
/deep/  .el-dialog__header{
  background-color: #fff;
}/deep/.el-dialog__headerbtn .el-dialog__close{
  color: #909399;
}

.materialIncountTable {
  border: 1px solid #eee;
  border-radius: 6px;
}
.materialIncountTableItem {
  display: flex;
  align-items: center;
  justify-content: space-around;
  border-bottom: 0.5px solid #eee;
}

</style>